﻿using System.Collections.Generic;

namespace IFramework
{
    public class Model : IModel
    {
        protected static volatile IModel instance;        //本类实例
        protected IDictionary<string, IProxy> proxyMap;   //代理集合类
        protected readonly object syncRoot = new object();//同步锁定对象（配合Lock关键字）
        protected static readonly object staticSyncRoot = new object();//静态同步锁定对象

		protected Model()
		{
			proxyMap = new Dictionary<string, IProxy>();
			InitializeModel();
		}
        static Model(){}
        public static IModel Instance{
            get{
                if (instance == null){
                    lock (staticSyncRoot){
                        if (instance == null) instance = new Model();
                    }
                }
                return instance;
            }
        }
        protected virtual void InitializeModel(){}

		public virtual void RegisterProxy(IProxy proxy){
			lock (syncRoot){
				proxyMap[proxy.ProxyName] = proxy;
			}
			proxy.OnRegister();
		}
		public virtual IProxy RetrieveProxy(string proxyName){
			lock (syncRoot){
				if (!proxyMap.ContainsKey(proxyName)) return null;
				return proxyMap[proxyName];
			}
		}

		public virtual bool HasProxy(string proxyName){
			lock (syncRoot){
				return proxyMap.ContainsKey(proxyName);
			}
		}
		public virtual IProxy RemoveProxy(string proxyName){
			IProxy proxy = null;
			lock (syncRoot){
				if (proxyMap.ContainsKey(proxyName)){
					proxy = RetrieveProxy(proxyName);
					proxyMap.Remove(proxyName);
				}
			}
  			if (proxy != null) proxy.OnRemove();
			return proxy;
		}
    }
}
